package com.tzx.rxbusdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tzx.rxbusdemo.common.BaseActivity;
import com.tzx.rxbusdemo.rx.bus.Event;
import com.tzx.rxbusdemo.rx.bus.ObjectEvent;
import com.tzx.rxbusdemo.rx.bus.RxBus;

import rx.Subscription;
import rx.functions.Func1;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static final String ACTION_MAIN_THREAD = "Main Thread";
    public static final String ACTION_NEW_THREAD = "New Thread";
    private TextView showValueTV;
    private EditText mainThreadET;
    private Button mainThreadBT;
    private EditText newThreadET;
    private Button newThreadBT;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showValueTV = (TextView) findViewById(R.id.show_tv);
        mainThreadET = (EditText) findViewById(R.id.main_value_tv);
        mainThreadBT = (Button) findViewById(R.id.main_value_btn);
        mainThreadBT.setOnClickListener(this);
        newThreadET = (EditText) findViewById(R.id.other_value_tv);
        newThreadBT = (Button) findViewById(R.id.other_value_btn);
        newThreadBT.setOnClickListener(this);
        initEventBus();
    }

    private void initEventBus() {
        Subscription s = RxBus.getInstance()
                .toObservableOnMain(ACTION_MAIN_THREAD)
                .subscribe(action -> showValueTV.setText(mainThreadET.getText().toString()));
        addSubscription(s);
        Subscription s1 = RxBus.getInstance()
                .toObservableOnMain(ACTION_NEW_THREAD)
                .map(event -> {
                    if (event instanceof ObjectEvent) {
                        return String.valueOf(((ObjectEvent) event).getObject());
                    }
                    return null;
                })
                .subscribe(this::updateTextView);
        addSubscription(s1);
    }

    private void updateTextView(CharSequence value) {
        showValueTV.setText(value);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_value_btn:
                this.runOnUiThread(() -> RxBus.getInstance().postEvent(() -> ACTION_MAIN_THREAD));
                break;
            case R.id.other_value_btn:
                Thread thread = new Thread(() -> {
                    RxBus.getInstance().postEvent(new ObjectEvent(ACTION_NEW_THREAD, newThreadET.getText().toString()));
                });
                thread.run();
                break;
        }
    }
}
